package com.example.yangguoying;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.example.yangguoying.datasource.DataSource;
import com.example.yangguoying.util.JDBC.JDBCAPI.JDBCUtilImpl;

import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    DataSource dataSource;
    JDBCUtilImpl jdbcUtil;
    EditText login_editText_account;
    EditText login_editText_password;
    Button login_button;
    CheckBox login_checkBox_remember;
    CheckBox login_checkBox_auto_login;
    Button login_text_goRegister;
    SharedPreferences.Editor dataEdit;
    SharedPreferences getDataEdit;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setView();
    }
    private void setView() {
        login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO
                login();
            }
        });

        //        监听点击记住密码选项
        login_checkBox_remember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                判断如果没有被选中记住密码，则将自动登录选框设置为false
                if (!isChecked){
                    login_checkBox_auto_login.setChecked(false);
                }
//                将记住密码和自动登录的选框状态进行保存
                dataEdit.putBoolean("isRemember",getRemember());
                dataEdit.putBoolean("isAutoLogin",getAutoLogin());
                dataEdit.commit();
            }
        });
//        监听自动登录选框
        login_checkBox_auto_login.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                如果自动登录选框被勾选，则将记住密码选框进行勾选
                if (isChecked){
                    login_checkBox_remember.setChecked(true);
                }
//                将记住密码和自动登录选框状态进行保存
                dataEdit.putBoolean("isRemember",getRemember());
                dataEdit.putBoolean("isAutoLogin",getAutoLogin());
                dataEdit.commit();
            }
        });
//        监听点击注册按钮,如果点击了注册按钮,则调用跳转到注册页面方法
        login_text_goRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToRegisterActivity();
            }
        });
    }
    @SuppressLint("CommitPrefEdits")
    private void initView() {
        login_editText_account = findViewById(R.id.login_editText_account);
        login_editText_password = findViewById(R.id.login_editText_password);
        login_button = findViewById(R.id.login_button);
        login_checkBox_auto_login = findViewById(R.id.login_checkBox_auto_login);
        login_checkBox_remember = findViewById(R.id.login_checkBox_remember);
        login_text_goRegister = findViewById(R.id.login_text_goRegister);
        dataSource = new DataSource();
        progressDialog = new ProgressDialog(LoginActivity.this);
        jdbcUtil = new JDBCUtilImpl(dataSource.getConnectionUrl(),dataSource.getDatabaseUser(),dataSource.getDatabasePassword(),"com.mysql.jdbc.Driver");
        dataEdit = getSharedPreferences("user_data",MODE_PRIVATE).edit();
        getDataEdit = getSharedPreferences("user_data",MODE_PRIVATE);
        if (getDataEdit.getBoolean("isRemember",false)){
            login_editText_account.setText(getDataEdit.getString("u_account",""));
            login_editText_password.setText(getDataEdit.getString("u_password",""));
            login_checkBox_remember.setChecked(getDataEdit.getBoolean("isRemember",false));
            login_checkBox_auto_login.setChecked(getDataEdit.getBoolean("isAutoLogin",false));
        }
//        如果是自动登录，则调用登录方法进行登录
        if (getDataEdit.getBoolean("isAutoLogin",false)){
            //TODO
            login();
        }

    }
    //    获取用户输入的账户
    private String getAccount(){
        return  login_editText_account.getText().toString();
    }
    //    获取用户输入的密码
    private String getPassword(){
        return  login_editText_password.getText().toString();
    }
    //  获取记住密码选框的状态
    private boolean getRemember(){
        return login_checkBox_remember.isChecked();
    }
    //  获取自动登录选框的状态
    private boolean getAutoLogin(){
        return login_checkBox_auto_login.isChecked();
    }

    private void goToRegisterActivity(){
        startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
    }
    private void setLocalStorage(){
//        判断是否勾选了记住密码，如果勾选了记住密码则将数据保存到本地
        if (getRemember()){
            dataEdit.putString("u_account",getAccount());
            dataEdit.putString("u_password",getPassword());
        }else{
//            如果没有勾选，则将账户密码设置为空
            dataEdit.putString("u_account","");
            dataEdit.putString("u_password","");
        }
//        提交保存的数据
        dataEdit.commit();
    }

    private void login(){
        //        获取到用户输入的账号
        String account = getAccount();
//        获取用户输入的密码
        String password = getPassword();
//设置标题信息
        progressDialog.setTitle("登录中....");
//设置ProgressDialog 是否可以按返回键取消；
        progressDialog.setCancelable(true);
        progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
//显示ProgressDialog
        progressDialog.show();
        final String[] queryAccount = new String[1];
        final String[] queryPassword = new String[1];
//        判断账户或者是密码是否为空
        if (!account.equals("") && !password.equals("")){
           new Thread(new Runnable() {
               @Override
               public synchronized void run() {
                   String sql = "SELECT * FROM android_users where user_name = ?";
                   Map<Object, Object> res = jdbcUtil.queryToMap(sql,new Object[]{account});
                   queryAccount[0] = (String) res.get("user_name");
                   queryPassword[0] = (String) res.get("user_password");
                   jdbcUtil.closeAll();
                   showResponse(account,password, queryAccount[0], queryPassword[0]);
               }
           }).start();
        }else{
            progressDialog.cancel();
            Toast.makeText(LoginActivity.this,"请填写账号密码！",Toast.LENGTH_SHORT).show();
        }
    }
    private void showResponse(String account,String password,String queryAccount,String queryPassword) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.cancel();
                if (account.equals(queryAccount) && password.equals(queryPassword)){
                    setLocalStorage();
                    startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this,"账号密码不正确！",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}